/**
 * 项目名：五位一体化工安全信息平台
 * 日期：    2019-12-06 15:05:44
 * Copyright (c) 2015- joysuch-版权所有
 */

package com.joysuch.wwyt.bp.service.impl;

import com.joysuch.wwyt.bp.bean.*;
import com.joysuch.wwyt.bp.bean.safetyworkcert.OperatorUserCertDto;
import com.joysuch.wwyt.bp.entity.BpWorkSafetyApplyFire;
import com.joysuch.wwyt.bp.entity.BpWorkSafetyApplyMethod;
import com.joysuch.wwyt.bp.entity.BpWorkSafetyApplyUser;
import com.joysuch.wwyt.bp.entity.BpWorkSafetyAudit;
import com.joysuch.wwyt.bp.entity.dsl.QBpWorkSafetyApplyFire;
import com.joysuch.wwyt.bp.enums.SafetyWorkStates;
import com.joysuch.wwyt.bp.enums.SafetyWorkTypes;
import com.joysuch.wwyt.bp.enums.UserTypes;
import com.joysuch.wwyt.bp.enums.WorkLevels;
import com.joysuch.wwyt.bp.repository.*;
import com.joysuch.wwyt.bp.service.BpWorkSafetyApplyFireService;
import com.joysuch.wwyt.bp.service.BpWorkSafetyApplyMethodService;
import com.joysuch.wwyt.bp.service.BpWorkSafetyApplyUserService;
import com.joysuch.wwyt.bp.service.BpWorkSafetyAuditService;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.common.util.PageDataUtils;
import com.joysuch.wwyt.core.common.util.PageDataUtils.PageDataConvert;
import com.joysuch.wwyt.core.common.util.SimpleDateFormatCache;
import com.joysuch.wwyt.core.enums.RiskLevels;
import com.joysuch.wwyt.core.exception.BusinessRestrictionsException;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.service.BaseAttachmentRepositoryService;
import com.joysuch.wwyt.core.service.BaseTypeGroupItemService;
import com.joysuch.wwyt.core.service.BizCodeGeneratorFacade;
import com.joysuch.wwyt.risk.bean.RiskPointControlRiskListSearchBean;
import com.joysuch.wwyt.risk.bean.RiskPointInDistrictListBean;
import com.joysuch.wwyt.risk.repository.RiskDistrictDao;
import com.joysuch.wwyt.risk.repository.RiskPointDao;
import com.joysuch.wwyt.risk.service.RiskPointService;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class BpWorkSafetyApplyFireServiceImpl implements BpWorkSafetyApplyFireService {

    @Autowired
    private BpWorkSafetyApplyFireDao dao;
    @Autowired
    private BizCodeGeneratorFacade bizCodeGeneratorFacade;
    @Autowired
    private RiskDistrictDao riskDistrictDao;
    @Autowired
    private RiskPointDao riskPointDao;
    @Autowired
    private RiskPointService riskPointService;

    @Autowired
    private BpWorkSafetyAuditDao bpWorkSafetyAuditDao;
    @Autowired
    private BpWorkSafetyAuditService bpWorkSafetyAuditService;
    @Autowired
    private BaseUserDao baseUserDao;
    @Autowired
    private BpWorkSafetyApplyUserDao bpWorkSafetyApplyUserDao;
    @Autowired
    private BpWorkSafetyApplyMethodDao bpWorkSafetyApplyMethodDao;
    @Autowired
    private BpWorkSafetyApplyMethodService bpWorkSafetyApplyMethodService;
    @Autowired
    private BpWorkSafetyApplyUserService bpWorkSafetyApplyUserService;

    @Autowired
    private BpDepartDao bpDepartDao;
    @Autowired
    private BaseAttachmentRepositoryService attachmentRepositoryService;
    @Autowired
    private BaseTypeGroupItemService baseTypeGroupItemService;
    @Autowired
    private BpWorkSafetyAuditDao workAuditDao;

//    @Override
//    public BpWorkSafetyApplyFire add(BpWorkSafetyApplyFireAddBean entity) throws Exception {
//        BpWorkSafetyApplyFire content = new BpWorkSafetyApplyFire();
//        // 作业证编号
//        if (StringUtils.isBlank(entity.getCode())) {
//            content.setCode(bizCodeGeneratorFacade.dongHuoZuoYe());
//        } else {
//            content.setCode(entity.getCode());
//        }
//        // 作业类型
//        content.setType(entity.getType());
//        // 作业级别
//        content.setWorkLevel(entity.getWorkLevel());
//        // 作业开始时间
//        content.setStartTime(entity.getStartTime());
//        // 作业结束时间
//        content.setEndTime(entity.getEndTime());
//        // 申请日期
//        if (entity.getApplyTime() == null) {
//            content.setApplyTime(new Date());
//        } else {
//            content.setApplyTime(entity.getApplyTime());
//        }
//        // 状态
//        content.setState(0);
//        // 申请单位
//        content.setApplyDepartId(entity.getApplyDepartId());
//        // 申请人
//        content.setApplyUserId(entity.getApplyUserId());
//        // 动火方式
//        content.setOpFireMethod(entity.getOpFireMethodId());
//        // 动火内容
//        content.setOpFireContent(entity.getOpFireContent());
//        // 动火地点
//        content.setOpFireLocationCoords(entity.getLocationCoords());
//        // 所属风险区域
//        content.setRiskDistrictId(entity.getRiskDistrictId());
//        // 生产单位负责人
//        content.setProductionDepartResponsibleUserId(entity.getProductionDepartResponsibleUserId());
//        // 动火作业负责人
//        content.setOpFireJobResponsibleUserId(entity.getOpFireJobResponsibleUserId());
//        // 动火初审人
//        content.setOpFireFirstAuditUserId(entity.getOpFireFirstAuditUserId());
//        // 监火人
//        // content.setOpFireMonitorUserId(entity.getOpFireMonitorUserId());
//        // 实施安全教育人
//        // content.setOpFireEducationUserId(entity.getOpFireEducationUserId());
//        // 风险点
//        content.setRiskPointId(entity.getRiskPointId());
//
//        content.setRiskLevel(entity.getRiskLevel());
//
//        // 附件
//        if (entity.getAttachment() != null) {
//            content.setAttachmentId(entity.getAttachment().getId());
//        }
//        // 危害辨识
//        content.setDangerRecoganize(entity.getDangerRecoganize());
//        // 编制人
//        content.setEditUserId(entity.getEditUserId());
//        dao.save(content);
//
//        // 保存动火人相关信息
//        saveOpFireUsers(content, entity.getOperatorUserCertDtos());
//        // 保存安全措施
//        saveOpMethods(content, entity.getSafetyMethods());
//
//        bpWorkSafetyAuditService.addOrUpdateWorkSafetyAudit(SafetyWorkTypes.DONG_HUO, content.getId(),
//                content.getCode(), content.getOpFireFirstAuditUserId());
//
//        return content;
//    }

    /**
     * 保存安全措施
     *
     * @param content
     *            动火操作实体
     * @param safetyMethods
     *            安全操作
     */
    private void saveOpMethods(BpWorkSafetyApplyFire content, List<BpWorkSafetyApplyMethodAddBean> safetyMethods) {
        if (safetyMethods != null && safetyMethods.size() > 0) {
            for (BpWorkSafetyApplyMethodAddBean bean : safetyMethods) {
                BpWorkSafetyApplyMethod entity = new BpWorkSafetyApplyMethod();
                entity.setWorkId(content.getId());
                entity.setConfirmUserId(bean.getConfirmUserId());
                entity.setMethod(bean.getMethod());
                entity.setType(SafetyWorkTypes.DONG_HUO.getName());
                bpWorkSafetyApplyMethodDao.save(entity);
            }
        }
    }

    /**
     * 保存动火人信息
     */
    private void saveOpFireUsers(BpWorkSafetyApplyFire content, List<OperatorUserCertDto> operatorUserCertDtos) {
        for (OperatorUserCertDto userCertDto : operatorUserCertDtos) {
            BpWorkSafetyApplyUser u = new BpWorkSafetyApplyUser();
            String type = userCertDto.getUserType();
            if (type != null) {
                UserTypes userType = UserTypes.findByCode(type);
                Assert.notNull(userType, "不能识别的人员类型");
                setUserDepartAndCertInfo(u, userType);
            }
            Integer userType1 = userCertDto.getPeopleType();
            if (userType1 != null) {
                if (userType1 == 1) {
                    u.setUserType("承包商");
                } else {
                    u.setUserType("内部");
                }
                UserTypes userType = UserTypes.findByName(u.getUserType());
//                    Assert.notNull(userType, "不能识别的人员类型");
                // 设置单位、证书信息
                setUserDepartAndCertInfo(u, userType);
            }
            u.setOpUserId(userCertDto.getUserId());
            u.setWorkId(content.getId());
            u.setType(SafetyWorkTypes.DONG_HUO.getName());
            bpWorkSafetyApplyUserDao.save(u);
        }
    }

    // 设置操作人单位、证书信息
    private void setUserDepartAndCertInfo(BpWorkSafetyApplyUser u, UserTypes userType) {
        if (userType == UserTypes.CONTRACTOR) {
            // 设置承包商信息
        } else {
            Long departId = baseUserDao.getOne(u.getOpUserId()).getDepartId();
            u.setDepartId(departId);
        }
    }

//    @Override
//    public void update(BpWorkSafetyApplyFireAddBean entity) throws Exception {
//        BpWorkSafetyApplyFire content = dao.findById(entity.getId()).get();
//        // 作业类型
//        content.setType(entity.getType());
//        // 作业级别
//        content.setWorkLevel(entity.getWorkLevel());
//        // 作业开始时间
//        content.setStartTime(entity.getStartTime());
//        // 作业结束时间
//        content.setEndTime(entity.getEndTime());
//        // 申请日期
//        content.setApplyTime(entity.getApplyTime());
//        // 申请单位
//        content.setApplyDepartId(entity.getApplyDepartId());
//        // 申请人
//        content.setApplyUserId(entity.getApplyUserId());
//        // 动火方式
//        content.setOpFireMethod(entity.getOpFireMethodId());
//        // 动火内容
//        content.setOpFireContent(entity.getOpFireContent());
//        // 动火地点
//        content.setOpFireLocationCoords(entity.getLocationCoords());
//        content.setRiskLevel(entity.getRiskLevel());
//        // 所属风险区域
//        content.setRiskDistrictId(entity.getRiskDistrictId());
//        // 生产单位负责人
//        content.setProductionDepartResponsibleUserId(entity.getProductionDepartResponsibleUserId());
//        // 动火作业负责人
//        content.setOpFireJobResponsibleUserId(entity.getOpFireJobResponsibleUserId());
//        // 动火初审人
//        content.setOpFireFirstAuditUserId(entity.getOpFireFirstAuditUserId());
//        // 监火人
//        // content.setOpFireMonitorUserId(entity.getOpFireMonitorUserId());
//        // 实施安全教育人
//        // content.setOpFireEducationUserId(entity.getOpFireEducationUserId());
//        // 风险点
//        content.setRiskPointId(entity.getRiskPointId());
//        // 附件
//        if (entity.getAttachment() != null) {
//            content.setAttachmentId(entity.getAttachment().getId());
//        }
//        // 危害辨识
//        content.setDangerRecoganize(entity.getDangerRecoganize());
//        // 编制人
//        content.setEditUserId(entity.getEditUserId());
//
//        dao.save(content);
//
//        // 删除动火人关联
//        bpWorkSafetyApplyUserDao.deleteByTypeAndWorkId(SafetyWorkTypes.DONG_HUO.getName(), content.getId());
//        // 删除安全措施关联
//        bpWorkSafetyApplyMethodDao.deleteByTypeAndWorkId(SafetyWorkTypes.DONG_HUO.getName(), content.getId());
//        // 保存动火人相关信息
//        saveOpFireUsers(content, entity.getOperatorUserCertDtos());
//        // 保存安全措施
//        saveOpMethods(content, entity.getSafetyMethods());
//
//        // 更新审批信息
//        bpWorkSafetyAuditService.addOrUpdateWorkSafetyAudit(SafetyWorkTypes.DONG_HUO, content.getId(),
//                content.getCode(), content.getOpFireFirstAuditUserId());
//    }

    @Override
    public Page<BpWorkSafetyApplyFireListBean> findByPage(Pageable page,
                                                          BpWorkSafetyApplyFireListSearchBean condition) {
        Predicate predicate = prepareListSearchCondition(condition);

        Page<BpWorkSafetyApplyFire> data = predicate == null ? dao.findAll(page) : dao.findAll(predicate, page);

        return PageDataUtils.convertPageData(data,
                new PageDataConvert<BpWorkSafetyApplyFireListBean, BpWorkSafetyApplyFire>() {

                    @Override
                    public BpWorkSafetyApplyFireListBean convert(BpWorkSafetyApplyFire f) {
                        BpWorkSafetyApplyFireListBean bean = new BpWorkSafetyApplyFireListBean();
                        // ID
                        bean.setId(f.getId());
                        // 作业证编号
                        bean.setCode(f.getCode());
                        // 作业类型
                        bean.setType(f.getType());
                        // 作业级别
                        bean.setWorkLevel(f.getWorkLevel());
                        bean.setWorkLevelName(WorkLevels.findNameById(f.getWorkLevel()));
                        if ("动火".equals(f.getType()) && f.getWorkLevel() == 0) {
                            bean.setWorkLevelName("特殊危险");
                        }
                        // 状态
                        bean.setState(f.getState());
                        bean.setStateName(parseStateName(f.getState()));

                        // 所属风险区域
                        bean.setRiskDistrictId(f.getRiskDistrictId());
                        bean.setRiskDistrictName(riskDistrictDao.getOne(f.getRiskDistrictId()).getName());

                        // 工作内容
                        bean.setWorkContent(f.getOpFireContent());
                        // 工作时间
                        bean.setWorkTime(parseWorkTime(f));
                        // 申请时间
                        bean.setApplyTime(SimpleDateFormatCache.getYmdZC().format(f.getApplyTime()));
                        if (f.getState() != null && f.getState() == 3) {
                            // 审核失败
                            bean.setAuditMsg(f.getAuditMsg());
                            bean.setAuditUser(baseUserDao.getBaseUserNameById(f.getOpFireFirstAuditUserId()));
                        }
                        return bean;
                    }

                });
    }

    protected String parseWorkTime(BpWorkSafetyApplyFire f) {
        return SimpleDateFormatCache.getYmdZC().format(f.getStartTime()) + " - "
                + SimpleDateFormatCache.getYmdZC().format(f.getEndTime());
    }

    protected String parseStateName(Integer state) {
        return SafetyWorkStates.findNameById(state);
    }

    private Predicate prepareListSearchCondition(BpWorkSafetyApplyFireListSearchBean condition) {
        QBpWorkSafetyApplyFire fire = QBpWorkSafetyApplyFire.bpWorkSafetyApplyFire;
        Predicate predicate = null;
        if (condition.getCodeOrLevel() != null) {
            predicate = fire.code.like("%" + condition.getCodeOrLevel() + "%");
            Integer level = null;
            if (condition.getCodeOrLevel().contains("一级")) {
                level = 1;
            } else if (condition.getCodeOrLevel().contains("二级")) {
                level = 2;
            } else if (condition.getCodeOrLevel().contains("特殊危险")) {
                level = 3;
            }
            if (level != null) {
                predicate = ExpressionUtils.or(predicate, fire.workLevel.eq(level));
            }
        }
        if (condition.getState() != null) {
            predicate = predicate == null ? fire.state.eq(condition.getState())
                    : ExpressionUtils.or(predicate, fire.state.eq(condition.getState()));
        }
        return predicate;
    }

    @Override
    public void delete(Long id) throws BusinessRestrictionsException {
        // 校验业务逻辑是否允许删除。如本数据被其他业务关联，删除后导致其他业务不可用。不能删除时将抛出业务异常
        checkBussinessRestrictions(id);
        dao.deleteById(id);
        workAuditDao.deleteByTypeAndWorkId(SafetyWorkTypes.DONG_HUO.getName(), id);
    }

    /**
     * 校验业务逻辑是否允许删除。如本数据被其他业务关联，删除后导致其他业务不可用
     *
     * @param id
     *            要删除的业务ID

     *             抛出的业务异常
     */
    private void checkBussinessRestrictions(Long id) throws BusinessRestrictionsException {

    }

    @Override
    public BpWorkSafetyApplyFire findById(Long id) {
        return dao.findById(id).get();
    }

//    @Override
//    public BpWorkSafetyApplyFireEditBean findDetailById(Long id) {
//        BpWorkSafetyApplyFireEditBean bean = new BpWorkSafetyApplyFireEditBean();
//        BpWorkSafetyApplyFire entity = dao.getOne(id);
//        bean.setId(entity.getId());
//        bean.setApplyTime(entity.getApplyTime());
//        bean.setApplyDepartId(entity.getApplyDepartId());
//        bean.setApplyDepartName(getDepartname(entity.getApplyDepartId()));
//        bean.setApplyUserName(baseUserDao.getBaseUserNameById(entity.getApplyUserId()));
//        bean.setState(entity.getState());
//        bean.setStateName(parseStateName(entity.getState()));
//        bean.setApplyUserId(entity.getApplyUserId());
//        if (entity.getAttachmentId() != null) {
//            bean.setAttachment(attachmentRepositoryService.findByIdIntoBean(entity.getAttachmentId()));
//        }
//        bean.setCode(entity.getCode());
//        bean.setDangerRecoganize(entity.getDangerRecoganize());
//        bean.setEditUserId(entity.getEditUserId());
//        bean.setEditUserName(baseUserDao.getBaseUserNameById(entity.getEditUserId()));
//        bean.setEndTime(entity.getEndTime());
//        bean.setStartTime(entity.getStartTime());
//        bean.setLocationCoords(entity.getOpFireLocationCoords());
//        bean.setOpFireContent(entity.getOpFireContent());
//        bean.setOpFireEducationUserName(baseUserDao.getBaseUserNameById(entity.getOpFireEducationUserId()));
//        bean.setOpFireEducationUserId(entity.getOpFireEducationUserId());
//        bean.setOpFireFirstAuditUserId(entity.getOpFireFirstAuditUserId());
//        bean.setOpFireFirstAuditUserName(baseUserDao.getBaseUserNameById(entity.getOpFireFirstAuditUserId()));
//
//        bean.setOpFireJobResponsibleUserId(entity.getOpFireJobResponsibleUserId());
//        bean.setOpFireJobResponsibleUserName(baseUserDao.getBaseUserNameById(entity.getOpFireJobResponsibleUserId()));
//
//        bean.setOpFireMethodId(entity.getOpFireMethod());
//        bean.setOpFireMethodName(baseTypeGroupItemService.findNameById(entity.getOpFireMethod()));
//
//        bean.setOpFireMonitorUserId(entity.getOpFireMonitorUserId());
//        bean.setOpFireMonitorUserName(baseUserDao.getBaseUserNameById(entity.getOpFireMonitorUserId()));
//        // 生产责任人
//        bean.setProductionDepartResponsibleUserName(
//                baseUserDao.getBaseUserNameById(entity.getProductionDepartResponsibleUserId()));
//        bean.setProductionDepartResponsibleUserId(entity.getProductionDepartResponsibleUserId());
//        // 风险区域
//        bean.setRiskDistrictId(entity.getRiskDistrictId());
//        bean.setRiskDistrictName(riskDistrictDao.getOne(entity.getRiskDistrictId()).getName());
//        // 查询风险点信息
//        RiskPointControlRiskListSearchBean c = new RiskPointControlRiskListSearchBean();
//        c.setRiskDistrictId(entity.getRiskDistrictId());
//        Page<RiskPointInDistrictListBean> data = riskPointService.findRiskPointsInDistrictPage(PageRequest.of(0, 1000),
//                c);
//        bean.setRiskPoints(ResultBean.pageData(data));
//
//        bean.setRiskPointId(entity.getRiskPointId());
//        bean.setRiskPointName(riskPointDao.getOne(entity.getRiskPointId()).getName());
//
//        bean.setWorkLevel(entity.getWorkLevel());
//        bean.setWorkLevelName(WorkLevels.findNameById(entity.getWorkLevel()));
//        if ("动火".equals(entity.getType()) && entity.getWorkLevel() == 0) {
//            bean.setWorkLevelName("特殊危险");
//        }
//        bean.setLocationCoords(entity.getOpFireLocationCoords());
//        bean.setType(entity.getType());
//        bean.setRiskLevel(entity.getRiskLevel());
//        bean.setRiskLevelName(RiskLevels.findRiskLevelName(entity.getRiskLevel()));
//
//        if (entity.getRiskLevel() != null) {
//            // EvalutionResult 和riskLevelName一个意思，只是为了兼容前端，后期可以考虑统一前后端字段命名，删除其中一个
//            bean.setEvalutionResult(bean.getRiskLevelName());
//        } else {
//            Integer riskLevel = riskPointDao.getOne(entity.getRiskPointId()).getRiskLevel();
//            bean.setRiskLevel(riskLevel);
//            bean.setRiskLevelName(RiskLevels.findRiskLevelName(riskLevel));
//            bean.setEvalutionResult(bean.getRiskLevelName());
//        }
//
//        bean.setOperatorUserCertNames(queryPeopleInfo(entity));
//        bean.setSafetyMethods(querySafetyMethods(entity));
//        // 设置验收信息
//        setCheckAndAuditInfo(bean, entity);
//        return bean;
//    }

    private void setCheckAndAuditInfo(BpWorkSafetyApplyFireEditBean bean, BpWorkSafetyApplyFire entity) {
        BpWorkSafetyAudit info = bpWorkSafetyAuditDao.findByTypeAndWorkId(SafetyWorkTypes.DONG_HUO.getName(),
                entity.getId());
        if (info == null) {
            return;
        }
        bean.setAuditState(info.getState());
        bean.setAuditMsg(info.getAuditMsg());
        if (info.getAuditTime() != null) {
            bean.setAuditTime(SimpleDateFormatCache.getYmdhms().format(info.getAuditTime()));
        }
        bean.setAuditUser(baseUserDao.getBaseUserNameById(info.getOpFireFirstAuditUserId()));
        bean.setCheckMsg(info.getCheckMsg());
        bean.setCheckState(info.getCheckState());
        bean.setCheckTime(null);
        if (info.getCheckTime() != null) {
            bean.setCheckTime(SimpleDateFormatCache.getYmdhms().format(info.getCheckTime()));
        }
        // bean.setCheckStateName(parseCheckStateName());
        bean.setCheckUser(baseUserDao.getBaseUserNameById(info.getCheckUserId()));
    }

    private List<BpWorkSafetyApplyUserDetailBean> queryPeopleInfo(BpWorkSafetyApplyFire entity) {
        return bpWorkSafetyApplyUserService.findUsersByCertTypeAndWorkId(SafetyWorkTypes.DONG_HUO, entity.getId());
    }

    private List<BpWorkSafetyApplyMethodEditBean> querySafetyMethods(BpWorkSafetyApplyFire entity) {
        return bpWorkSafetyApplyMethodService.findByCertTypeAndId(SafetyWorkTypes.DONG_HUO, entity.getId());
    }

    private String getDepartname(Long departId) {
        if (departId != null) {
            return bpDepartDao.getOne(departId).getName();
        }
        return null;
    }

}
